package club.twelveblog.tblog.controller;

import club.twelveblog.tblog.common.constants.HttpStatusConstants;
import club.twelveblog.tblog.common.constants.SessionConstants;
import club.twelveblog.tblog.common.dto.Result;
import club.twelveblog.tblog.common.dto.userResult;
import club.twelveblog.tblog.common.enums.ExceptionEnum;
import club.twelveblog.tblog.common.exception.BlogException;
import club.twelveblog.tblog.entity.BlogInfo;
import club.twelveblog.tblog.entity.Category;
import club.twelveblog.tblog.entity.Comment;
import club.twelveblog.tblog.entity.User;
import club.twelveblog.tblog.service.BlogInfoService;
import club.twelveblog.tblog.service.CommentService;
import club.twelveblog.tblog.service.UserService;
import club.twelveblog.tblog.utils.Token;
import club.twelveblog.tblog.utils.ValidateCode;
import club.twelveblog.tblog.utils.changeDate;
import club.twelveblog.tblog.utils.ResultGenerator;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("tblog/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private BlogInfoService blogInfoService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private changeDate changDate;
    @Autowired
    private ValidateCode validateCode;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private Token token;
    @Autowired
    private userResult userresult;

    private Cookie cookie;
    /**
     * 根据用户id查找指定用户个人信息
     * @param
     * @return
     */
    @GetMapping("/show")
    public Result<User> findUserById(){
        try{
            //根据从redis获得的user_id进行查库
            Optional<User> user = userService.findUserById(SessionConstants.USER_ID);
            if(!user.isPresent()){
                throw new BlogException(ExceptionEnum.USER_NOT_FOUND);
            }
            return ResultGenerator.getResultByHttp(HttpStatusConstants.OK,user.get());
        }catch (BlogException e){
            throw new BlogException(ExceptionEnum.USERS_NOT_FOUND);
        }
    }

    /**
     * 修改用户个人信息
     *传过来的用户id为SessionConstants.USER_ID
     * @param user
     * @return
     */
    @PatchMapping
    public Result updateUserInfo(User user) {
        if(user.getUser_id()==null){
            throw new BlogException(ExceptionEnum.BAD_PARAM_REQUEST);
        }if(userService.getOne(user.getUser_id())==null){
            throw new BlogException(ExceptionEnum.USER_NOT_FOUND);
        }
        try {
            userService.updateUserInfo(user);
        } catch (BlogException e) {
        throw new BlogException(ExceptionEnum.UPDATE_FAILED);
    }
        return ResultGenerator.getResultByHttpNoData(HttpStatusConstants.UPDATE_SUCCESS);
    }

    /**
     * 已登录用户发表文章
     * @param blogInfo
     * @param category_id
     * @return
     */
    @PostMapping(value = "/editArticle")
    public Result editArticle(BlogInfo blogInfo, @RequestParam(name = "category_id") Long category_id) {
        blogInfoService.saveBlogInfo(blogInfo,category_id);
        return ResultGenerator.getResultByHttpNoData(HttpStatusConstants.OK);
    }

    /**
     * 用户头像上传
     * @param file
     * @return
     */
    @PostMapping("/icon")
    @ResponseBody
    public Result UploadUserImg(@RequestParam(value="file") MultipartFile file){
        List<String> ALLOW_IMAGE_TYPE = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/gif");

        try {
            //校验文件类型
            String contentType = file.getContentType();
            if (!ALLOW_IMAGE_TYPE.contains(contentType)) {
                throw new BlogException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //校验文件内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                throw new BlogException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            String url=userService.UploadUserImg(file);
            //调用userService方法更新用户头像信息
            userService.updateImage(url);
            return ResultGenerator.getResultByHttp(HttpStatusConstants.UPLOAD_SUCCESS,url);
        }catch (IOException e) {
            throw new BlogException(ExceptionEnum.UPLOADIMAGE_ERROR);
        }

    }

    /**
     * 查询当前用户下的所有已发布的文章
     * @param page
     * @return
     */
    @GetMapping("/article")
    public Result<List<BlogInfo>> getBlogInfoByUserName( @RequestParam(name = "page", defaultValue = "1") int page) {
        Page<List<BlogInfo>> blogInfos = blogInfoService.findMyBlogInfo(page);
        if (blogInfos.isEmpty()) {
            throw new BlogException(ExceptionEnum.ERROR_QUERY_BLOGINFO);
        }
        return ResultGenerator.getResultByHttp(HttpStatusConstants.OK,blogInfos);
    }

    /**
     * 查找用户的所有评论
     * @param user_id
     * @return
     */
    @GetMapping("/myComment")
    public Result<List<Comment>> findMyComments(@RequestParam(name = "user_id") Long user_id){
        List<Comment> comments= commentService.findMyComments(user_id);
        return ResultGenerator.getResultByHttp(HttpStatusConstants.OK,comments);
    }

}
